package com.study.ws.config.ws.session_manager;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 基于内存的一个会话管理系统
 *
 * @author xl-9527
 * @since 2025/3/25
 **/
@Component
public class LocalMemorySessionManagerWithWebSocketSession implements ISessionManager<WebSocketSession> {

    private static final Map<Integer, WebSocketSession> SESSION_MAPPING = new ConcurrentHashMap<>();

    @Override
    public void addSession(final WebSocketSession session, final Integer userId) {
        SESSION_MAPPING.put(userId, session);
    }

    @Override
    public void removeSession(final Integer userId) {
        try (WebSocketSession session = SESSION_MAPPING.remove(userId)) {
            if (!Objects.isNull(session)) {
                final TextMessage message = new TextMessage("server: userId[" + userId + "] is offline");
                for (final WebSocketSession webSocketSession : this.getAllSession()) {
                    if (webSocketSession.isOpen()) {
                        webSocketSession.sendMessage(message);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public WebSocketSession getSession(final Integer userId) {
        return SESSION_MAPPING.get(userId);
    }

    @Override
    public Integer getUserId(final WebSocketSession session) {
        for (Map.Entry<Integer, WebSocketSession> entry : SESSION_MAPPING.entrySet()) {
            if (entry.getValue().equals(session)) {
                return entry.getKey();
            }
        }
        throw new RuntimeException("userId not found");
    }

    @Override
    public Collection<WebSocketSession> getAllSession() {
        return SESSION_MAPPING.values();
    }
}
